//第二版 2011-01-10 ,增加模板与代码类别
pickerContainer = {
    name: [],
    content: []
};
function fundPicker(id, option) {
	id = (!!(id && id.nodeType == 1))?id:document.getElementById(id);
    if (!getFundPicker(id)) {
        pickerContainer.name[pickerContainer.name.length] = id;
        pickerContainer.content[pickerContainer.content.length] = new autoPicker(id, option);
        return pickerContainer.content[pickerContainer.content.length - 1]
    }
	else
	{
		return getFundPicker(id);
	}
}


function getFundPicker(id)
{
	if (pickerContainer == null) pickerContainer = {
        name: [],
        content: []
    };
	id = (!!(id && id.nodeType == 1))?id:document.getElementById(id);
    for (var i = 0; i < pickerContainer.name.length; i++) {
        if (pickerContainer.name[i] == id) return pickerContainer.content[i]
    }
    if (i >= pickerContainer.name.length) {
        return false;
    }
}

(function(){
  var cache = {};
 
  window.tmpl = function tmpl(str, data){
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
        "with(obj){p.push('" +
        str
          .replace(/[\r\t\n]/g, " ")
          .split("<%").join("\t")
          .replace(/((^|%>)[^\t]*)'/g, "$1\r")
          .replace(/\t=(.*?)%>/g, "',$1,'")
          .split("\t").join("');")
          .split("%>").join("p.push('")
          .split("\r").join("\\'")
      + "');}return p.join('');");   
    return data ? fn( data ) : fn;
  };
})(); 

function IsWhat(value) {
    if (IsChinese(value)) return {
        Type: 0,
        name: "名称"
    };
    else if (IsNumber(value)) return {
        Type: 1,
        name: "代码"
    };
    else return {
        Type: 2,
        name: "拼音"
    }
}

function IsChinese(value) {
    value = value.charAt(0);
    var escape_v = escape(value);
    if (escape_v.length == (value.length) * 6 || value == "\r" || value == "\n") return true;
    else return false
}
function IsNumber(value) {
    var num = parseInt(value);
    if (num == 0 || num) return true;
    else return false
}
function IsCode(value){
	for(var i = 0;i<value.length;i++){
		if(!IsNumber(value.substr(i,1))){
			return false;
		}
	}
	return true;
}

function Trim(value) {
    return value.replace(/^\s+|\s+$/g, "")
}



autoPicker.GetEventFrom = function(e) {
    var ele;
    ele = e.target ? e.target: e.srcElement;
    return ele
}
autoPicker.Bind = function(object, fun) {
    var args = Array.prototype.slice.call(arguments).slice(2);
    return function() {
        return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)))
    }
}
autoPicker.BindAsEventListener = function(object, fun) {
    var args = Array.prototype.slice.call(arguments).slice(2);
    return function(e) {
        return fun.call(object, (e || window.event), args)
    }
}
autoPicker.attachEventHandle = function(elem, eventName, func) {
    if (window.attachEvent) {
        elem.attachEvent('on' + eventName, func)
    } else if (window.addEventListener) {
        elem.addEventListener(eventName, func, false)
    }
}
autoPicker.detachEventHandle = function(elem, eventName, func) {
    if (window.detachEvent) {
        elem.detachEvent('on' + eventName, func)
    } else if (window.removeEventListener) {
        elem.removeEventListener(eventName, func, false)
    }
}
autoPicker.getPosition = function(elem) {
    var x = 0,
    y = 0;
    while (elem) {
        x += elem.offsetLeft || 0;
        y += elem.offsetTop || 0;
        elem = elem.offsetParent
    }
    return {
        x: x,
        y: y
    }
}
autoPicker.extend = function(destination, source) {
    for (property in source) {
        destination[property] = source[property]
    }
    return destination;
}
function autoPicker(id, option,data) {
	this.dataSource=data;
    this.option = autoPicker.extend({
        domDefaultValue: "代码/名称/拼音",
        maxLength: 20,
        listClass: "autoPicker_listDiv",
        listTitleClass: "autoPicker_listTitle",
        selectClassName: "autoPicker_selectClassName",
        viewValue: "name",
        returnValue: "code",
		datatype:{'0':{name:"深市",code:'sz'},'1':{name:"沪市",code:"sh"},'2':{name:"基金",code:"fund"}},
		seachData:null,
		Data:this.dataSource
    },
    option);
    this.$Dom = ( !! (id && id.nodeType == 1)) ? id: document.getElementById(id);
    this.$Div = this.$Dom.parentNode.insertBefore(document.createElement('div'), this.$Dom);
    this.$Div.className = this.option.listClass;
    with(this.$Div.style) {
        zIndex = 9999999;
        position = 'absolute';
        margin = '0';
        left = autoPicker.getPosition(this.$Dom).x + 'px';
        top = autoPicker.getPosition(this.$Dom).y + this.$Dom.offsetHeight + 'px';
        display = "none"
    }
	this.divHasFoucs = false;
    this.selectValue = "";
    this.selectData = [];
    this.selectNum = -1;
	this.selectValue=this.$Dom.value;
    this.getData();
	if(this.selectData.length ==0)
	{
		this.option.domDefaultValue = this.$Dom.value;
		this.clearDom();
		this.selectValue = "";
		this.getData();
	}
	
    autoPicker.attachEventHandle(this.$Dom, "focus", autoPicker.Bind(this, this.apFoucs));
    autoPicker.attachEventHandle(this.$Dom, "blur", autoPicker.Bind(this, this.apBlur));
    autoPicker.attachEventHandle(this.$Dom, "click", autoPicker.Bind(this, this.showDiv));
    autoPicker.attachEventHandle(this.$Dom, "keyup", autoPicker.BindAsEventListener(this, this.apKeyUp));
    autoPicker.attachEventHandle(this.$Dom, "keydown", autoPicker.BindAsEventListener(this, this.apKeyDown));
    autoPicker.attachEventHandle(this.$Div, "click", autoPicker.BindAsEventListener(this, this.adClick));
    autoPicker.attachEventHandle(this.$Div, "mouseover", autoPicker.BindAsEventListener(this, this.adMouseOver));
	autoPicker.attachEventHandle(this.$Div, "focus", autoPicker.BindAsEventListener(this, this.divFoucs));
	autoPicker.attachEventHandle(this.$Div, "blur", autoPicker.BindAsEventListener(this, this.divBlur));
	autoPicker.attachEventHandle(this.$Div, "mousedown", autoPicker.BindAsEventListener(this, this.divFoucs));
	autoPicker.attachEventHandle(this.$Div, "mouseup", autoPicker.BindAsEventListener(this, this.divMouseUp));
}
autoPicker.prototype = {
	divFoucs: function ()
	{
		this.divHasFoucs = true;
	},
	divBlur: function ()
	{
		this.divHasFoucs = false;
		this.apBlur();
	},
	divMouseUp:function()
	{
		this.divHasFoucs = false;
	}
	,
    adClick: function(e) {
		var temp = autoPicker.GetEventFrom(e).nodeName.toUpperCase() == "b".toUpperCase()?autoPicker.GetEventFrom(e).parentNode:autoPicker.GetEventFrom(e);
		if(temp.parentNode.parentNode.nodeName.toUpperCase() == "tbody".toUpperCase()){
		this.divHasFoucs = false;
        this.selectCurrentResult()
		}else{
			this.$Dom.focus();
		}
    },
    getValue: function() {
        var p = {
            hasValue: false
        }
        p.code = this.$Dom.getAttribute("code");
        p.value = this.$Dom.value;
        if (p.code != "" && p.code != null) p.hasValue = true;
        return p
    },
    setValue: function(value) {
        this.$Dom.value = (value != null) ? value: "";
        this.$Dom.setAttribute("code", "");
        this.apMust();
        this.setDom()
    },
    adMouseOver: function(e) {
        var tempDom = autoPicker.GetEventFrom(e);
        tempDom = tempDom.parentNode;
        if (tempDom.nodeName.toLowerCase() == "tr") {
            var j;
            for (j = 0; j < tempDom.parentNode.children.length; j++) {
                if (tempDom == tempDom.parentNode.children[j]) break
            }
            if (j < tempDom.parentNode.children.length) {
                this.selectNow(j)
            }
        }
    },
    selectNow: function(i) {
		if(this.selectData.length<=0)
		return;
        var tempClassName;
        tempClassName = this.$Div.children[0].children[1].children[this.selectNum].className;
        tempClassName = tempClassName.replace(this.option.selectClassName, "");
        this.$Div.children[0].children[1].children[this.selectNum].className = tempClassName;
        this.selectNum = i;
        this.showSelect()
    },
    showDiv: function() {
        this.$Div.style.display = 'block';
        var html = '';
        this.selectNum = this.selectData.length > 0 ? 0: -1;
        for (var i = 0, len = this.selectData.length; i < len; i++) {
            var tempDataName = this.selectData[i].showName?this.selectData[i].showName:this.selectData[i][0];
            var tempDataCode = this.selectData[i][1],tempDataType;
			try{
				tempDataType = this.option.datatype[this.selectData[i][3]].name;
			}
			catch(ee){
				
			}
            if(this.selectValue.length>0&&IsCode(this.selectValue)){
				tempDataName = tempDataName.replace(this.selectValue,"<b>" + this.selectValue + "</b>");
				tempDataCode = tempDataCode.replace(this.selectValue,"<b>" + this.selectValue + "</b>");
			}
            html += "<tr><td>" + tempDataCode + "</td><td>" + tempDataName + "</td><td>"+tempDataType+"</td></tr>"
        }
        if (html == '') html = "<div class='" + this.option.listTitleClass + "'>没有 '<i>" + this.selectValue + "</i>' 相关的数据</div>";
        else if (this.selectValue == "") html = "<table cellpadding=0 cellspacing=0><thead><tr><td style='width:4em'>代码</td>    <td>名称</td>    <td style='width:2.5em'>类别</td></tr></thead><tbody>" + html + "</tbody></table>";
        else html = "<table cellpadding=0 cellspacing=0><thead><tr><td style='width:4em'>代码</td>    <td>名称</td>    <td style='width:2.5em'>类别</td></tr></thead><tbody>" + html + "</tbody></table>";
        this.$Div.innerHTML = html;
        this.showSelect()
    },
    showSelect: function() {
        if (this.selectNum < 0) return;
        var tempClassName;
        tempClassName = this.$Div.children[0].children[1].children[this.selectNum].className;
        tempClassName = tempClassName.replace(this.option.selectClassName, "");
        tempClassName = tempClassName + " " + this.option.selectClassName;
        this.$Div.children[0].children[1].children[this.selectNum].className = tempClassName
    },
    hideDiv: function() {
		if(!this.divHasFoucs)
        this.$Div.style.display = 'none'
    },
    clearDom: function() {
        if (this.$Dom.value == Trim(this.option.domDefaultValue)) {
            this.$Dom.value = ""
        }
    },
    setDom: function() {
        if (Trim(this.$Dom.value) == '') {
            this.$Dom.value = this.option.domDefaultValue
        }
    },
    apFoucs: function() {
        this.clearDom();
        this.$Dom.select();
        this.refreshDiv(true)
    },
    apBlur: function() {
		if(!this.divHasFoucs){
        setTimeout(autoPicker.Bind(this, this.hideDiv), 100);
        this.apMust();
        this.setDom();
		}
    },
    apMust: function() {
        var p = this.getValue();
        if (!p.hasValue && p.value != "") {
           this.getData();
		var codetype;
		for(var i = 0;i<this.selectData.length;i++){
			if(IsCode(this.selectValue)){
				codetype = 1;
			} else {
				codetype = 0;
			}
			
			if(this.option.Data[i][0].length == this.selectValue.length){
				break;
			}
		}
		
		if(i<this.selectData.length){
			this.selectNum = i;
			if (this.selectNum >= 0 && this.selectNum < this.selectData.length) {
            this.$Dom.title = this.option.datatype[this.selectData[this.selectNum][3]].code+this.selectData[this.selectNum][1];
            this.$Dom.value = this.selectData[this.selectNum][0];
            this.$Dom.setAttribute("code", this.option.datatype[this.selectData[this.selectNum][3]].code+this.selectData[this.selectNum][1]);
            this.apBlur();
        }
		}
        }
		
		
		
    },
    prevResult: function() {
        if (this.selectNum > 0) this.selectNow(this.selectNum - 1);
        else this.selectNow(this.selectData.length - 1)
    },
    nextResult: function() {
        if (this.selectNum < this.selectData.length - 1) this.selectNow(this.selectNum + 1);
        else this.selectNow(0)
    },
    selectCurrentResult: function() {
        if (this.selectNum >= 0 && this.selectNum < this.selectData.length) {
            this.$Dom.title = this.option.datatype[this.selectData[this.selectNum][3]].code+this.selectData[this.selectNum][1];
            this.$Dom.value = this.selectData[this.selectNum][0];
            this.$Dom.setAttribute("code", this.option.datatype[this.selectData[this.selectNum][3]].code+this.selectData[this.selectNum][1]);
            this.apBlur();
            if (this.option.callBack) {this.option.callBack(this.getValue(),this)};
        }
    },
    getData: function() {
		var i,j,m,n,y;
        this.selectData.length = 0;
        if (this.selectValue == "") {
			if(this.option.hotData)
			{
				for (j = 0; j < this.option.maxLength&&j<this.option.hotData.length; j++) {
                this.selectData[j] = this.option.hotData[j]
            	}
			}
			else
			{
            for (j = 0; j < this.option.maxLength&&j<this.option.Data.length; j++) {
                this.selectData[j] = this.option.Data[j]
            }
			}
        } else {
            var p=[],bz;
			if(IsCode(this.selectValue)){
				for(i = 0;i<this.option.Data.length&&this.selectData.length<this.option.maxLength;i++){
					bz=-1;
					m = this.option.Data[i][1].indexOf(this.selectValue);
					n = this.option.Data[i][0].indexOf(this.selectValue);
					if(m==0||n==0){bz=0}
					else if(m>0||n>0){bz=1};
					
					if(bz===0){
						this.selectData.push(this.option.Data[i]);
					}else if(bz>0){
						p.push(this.option.Data[i]);
					}
				}
			}else{
				var o=[],s,q,k;
				q = this.selectValue;
				for(y = 0;y<this.option.Data.length&&this.selectData.length<this.option.maxLength;y++){
					o.length = 0;
					s=this.option.Data[y];
					for(var i=0;i<s[0].length;i++){
						for(j=0;j<q.length;j++){
							var type = IsNumber(q.substr(j,1))||IsChinese(q.substr(j,1))?0:2;
							if(!(q.substr(j,1)=="?"&&s[type].substr(i+j,1)||s[type].substr(i+j,1).toLowerCase() == q.substr(j,1).toLowerCase())){
							break;}
						}
						if(j==q.length){
							o.push(i);
							i+=j-1;
						}
					}
					c=s[0];
					for(k=0;k<o.length; k++){
						if(k==0){c=s[0].substr(0,o[k]);};
						c+="<b>"+s[0].substr(o[k],q.length)+"</b>";
						if(o.length>k+1){
						c+=s[0].substring(o[k]+q.length,o[k+1]);
						}
						else {
						c+=s[0].substr(o[k]+q.length);
						var n=[];
							n=autoPicker.extend(n,this.option.Data[y]);
						    n.showName = c;
							if(o[0]==0){
						this.selectData.push(n);
							}else{
								p.push(n);
							}
						}
					}
				}
			}
			for(j=0;this.selectData.length<this.option.maxLength&&j<p.length;j++){
					this.selectData.push(p[j]);
			}
		}
    },
    refreshDiv: function(enb) {
        var temp = Trim(this.$Dom.value);
        if (!enb) enb = false;
        if (this.selectValue != temp || this.selectValue == "") {
            this.selectValue = temp;
            this.getData();
            this.$Dom.title = "";
            this.$Dom.setAttribute("code", "");
            enb = true
        }
        if (enb) this.showDiv()
    },
    apKeyDown: function(e) {
        if (e.keyCode == 13) {
            this.selectCurrentResult();
            if (e.preventDefault) e.preventDefault();
            if (e.stopPropagation) e.stopPropagation();
            if (typeof(e.cancelBubble) !=="undefined") {
                e.cancelBubble = true;
                e.returnValue = false;
            }
        }
    },
    apKeyUp: function(e) {
        if (e.keyCode == 38 || e.keyCode == 40 || e.keyCode == 27) {
            switch (e.keyCode) {
            case 38:
                this.prevResult();
                break;
            case 40:
                this.nextResult();
                break;
            case 27:
                this.hideDiv();
                break
			}
        } else {
            this.refreshDiv(true)
        }
    }
}

